package com.gopay.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.gopay.common.constants.cust.SMSType;
import com.gopay.common.cps.dao.cbrmb.CbRmbTranAssistDtlDao;
import com.gopay.common.domain.cbrmb.CbRmbTranAssistDtl;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.service.cbrmb.CbRmbPayForCcbService;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.constants.SMSResCode;
import com.gopay.sms.common.domain.RequestVO;
import com.gopay.sms.common.domain.ResponseVO;
import com.ibm.icu.math.BigDecimal;

/**
 * 
 * @ClassName: CbRmbPayForCcbAmtWarnJob
 * @Description: 跨境人民币 报盘前通知运营人员去拨款  11:00和下午3:30各拨一次款
 * @author gd.cui
 * @date 2016年6月29日 下午4:27:03 ww.gopay.com.cn Inc.All rights reserved.
 */
public class CbRmbPayForCcbAmtWarnJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private @Value("#{webProperties['cbrmbMobile']}") String mobile;

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Override
    protected void doJobInternal() {
        /**
         * 现在暂时一天跑2次，11:30的跑11:00之前的订单，下午4:00的跑3:30之前的
         */
        if (isWorkDay()) {
            logger.info("=======start CbRmbPayForCcbAmtWarnJob  ===========");
            Calendar c = Calendar.getInstance();
            int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH)+1;
            int day=c.get(Calendar.DATE);
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
            Date nowTime = c.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date11 = new Date(nowTime.getYear(), nowTime.getMonth(), nowTime.getDate(), 11, 00);
            Date date330 = new Date(nowTime.getYear(), nowTime.getMonth(), nowTime.getDate(), 15, 30);
            // String hql = "from CbRmbTranAssistDtl where state=:state";
            // 已经发生退款的汇款类订单不要去报盘了,edit by qld 20160810
            // 在20161109再次修改逻辑，汇款充值的reid=汇款的订单号，汇款充值退款的reid=汇款充值的，所以2个关联获取该笔汇款订单是否发生退款
            // 这个要修改准备，在报盘表中加上一个状态03，报盘订单发生退款
            String sql = "select sum(b.mer_txn_amt),'' from cb_rmb_tran_assist_dtl a,cps_gen_main_order b where not exists(select 1 from cps_gen_main_order t " +
            		"where t.relevance_gopay_order_id=a.gopay_order_id  and t.gopay_int_txn_cd in('01728','01730') and t.txn_sta_cd!='20003')" +
            		"and not exists(select 1 from cps_gen_main_order t,cps_gen_main_order tk where a.gopay_order_id=t.relevance_gopay_order_id " +
            		"and tk.relevance_gopay_order_id=t.gopay_order_id" +" and tk.gopay_int_txn_cd='01733' and tk.txn_sta_cd!='20003') " +
            				" and  a.gopay_order_id=b.gopay_order_id and b.gopay_txn_tm<=to_date(:stime,'yyyy-MM-dd hh24:mi:ss')  and a.state=:state";
            Map<String, Object> param = new HashMap<String, Object>();
            param.put("state", "01");
            if (hour == 11 && minute == 00) {// 11:00的
                param.put("stime", sdf.format(date11));
                List<Object[]> list = commonQueryDAO.findBySql(sql, param);
                if(list!=null&&list.get(0)!=null){
                  BigDecimal totalAmt=new BigDecimal(list.get(0)[0].toString()); 
                  if(totalAmt.compareTo(BigDecimal.ZERO)>0){
                  sendSmsNotify("跨境支付业务于"+year+"年"+month+"月"+(day-1)+"日15：30至"+year+"年"+month+"月"+day+"日11：00产生的跨境交易总金额为"+totalAmt+"元，烦请向跨境专户备款，谢谢！");
                  }
                }
                
            } else if (hour == 15 && minute == 30) {//3:30
                param.put("stime", sdf.format(date330));
                List<Object[]> list = commonQueryDAO.findBySql(sql, param);
                if(list!=null&&list.get(0)!=null){
                  BigDecimal totalAmt=new BigDecimal(list.get(0)[0].toString()); 
                  logger.info("总金额:"+totalAmt);
                  if(totalAmt.compareTo(BigDecimal.ZERO)>0){
                  sendSmsNotify("跨境支付业务于"+year+"年"+month+"月"+day+"日11：00至15:30产生的跨境交易总金额为"+totalAmt+"元，烦请向跨境专户备款，谢谢！");
                  }
                }
            }else{
                logger.info("这个时间不跑定时任务去报盘");
            }

        } else {
            logger.info(" ======= 非工作时间，抱歉哦！ ===========");

        }
    }

    private boolean isWorkDay() {
        Calendar c = Calendar.getInstance();
        int week = c.get(Calendar.DAY_OF_WEEK);// 23456工作日
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        if (2 <= week && week <= 6) {
            if (hour >= 9 && hour <= 16) {
                return true;
            }
            // if (hour == 16 && minute < 30) {
            // return true;
            // }
        }
        return false;
    }
    /**
     * 发送短信
     * 
     * @param mobileNo
     * @param smsType
     * @return
     */
    private void sendSmsNotify(String content){
        try {
            RequestVO req = new RequestVO();
            req.setAppId(SMSAppId._90000.value);
            req.setMobile(mobile);//如果发送多个手机号码时，可使用逗号进行隔开。
            req.setContent(content);
            GopaySMSHttpClient.getInstance().createVerificationCode(req);
        } catch (Exception e) {
           // e.printStackTrace();
            logger.error("发送短信通知时异常", e);
        }
    }
}
